package com.maltys.tree;

import com.maltys.tree.base.TreeNode;

/**
 * @author malty
 * @link <a href="https://leetcode.cn/problems/delete-node-in-a-bst/description/">...</a>
 */
public class DeleteNodeInBst {
    public TreeNode deleteNode(TreeNode root, int key) {
        if (root == null) {
            return root;
        }

        if (root.val == key) {
            if (root.left == null && root.right == null) {
                return null;
            }
            if (root.left != null && root.right != null) {
                traverse(root.right, root.left);
                return root.right;
            }
            if (root.left == null) {
                return root.right;
            }
            if (root.right == null) {
                return root.left;
            }
        }
        if (root.val > key) {
            root.left = deleteNode(root.left, key);
        }
        if (root.val < key) {
            root.right = deleteNode(root.right, key);
        }
        return root;
    }

    private void traverse(TreeNode root, TreeNode sub) {
        if (root.left != null) {
            traverse(root.left, sub);
        } else {
            root.left = sub;
        }
    }

}
